package net.pimpas.web.jsf.renderers.group.ajax;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.render.Renderer;

import net.pimpas.web.jsf.components.ajax.context.ResponseWriterAjaxWrapper;
import net.pimpas.web.jsf.components.group.UIGroup;
import net.pimpas.web.jsf.renderers.AjaxRendererBase;
import net.pimpas.web.jsf.renderers.group.html.HtmlGroupRenderer;
import net.pimpas.web.jsf.renderers.html.ajax.AjaxHtmlRenderer;
import net.pimpas.web.jsf.util.ComponentUtils;

import org.dom4j.Node;

public class AjaxGroupRenderer extends AjaxHtmlRenderer {
	
	@Override
	protected Renderer getRenderer(FacesContext context, UIComponent component) {
		return new AjaxGroupRendererHelper();
	}
	
	@Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		// change id
		ResponseWriterAjaxWrapper wrapper = (ResponseWriterAjaxWrapper) context.getResponseWriter();
		Node element = wrapper.getElement();
		Node id = element.selectSingleNode("id");
		UIComponent content = ComponentUtils.getComponentById(component, context, component.getId()+UIGroup.CONTENT_ID, ComponentUtils.SERVER_ID);
		id.setText(content.getClientId(context));
		
		super.encodeEnd(context, component);
	}
	
	public static final class AjaxGroupRendererHelper extends AjaxHtmlRenderer implements AjaxRendererBase {
		
		@Override
		public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
			HtmlGroupRenderer.renderContent(context, component);
		}
	}
}